//
//  MyConsulationListViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/23.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "MyConsulationListViewController.h"

#import "ConsulationV2AnswerInfoViewController.h"

#import "EPMainTabsView.h"

#import "ConsulationAnsedListCell.h"

@interface MyConsulationListViewController () <UITableViewDelegate, UITableViewDataSource>

/// 模型视图
@property (nonatomic, readonly, strong) MyConsulationListViewModel* viewModel;

@property (nonatomic, copy) NSArray* tableViews;

// UI

//IBOutlet
@property (weak, nonatomic) IBOutlet UIView* tabsView;
@property (weak, nonatomic) IBOutlet UIScrollView* tableScrollView;

@end

@implementation MyConsulationListViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self _setupAllViewInViewLoad];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    NSLog(@"viewDidLayoutSubviews");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        NSLog(@"viewDidAppear");
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
        
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[[viewDidLayoutSVSignal take:1] zipWith:[willAppearSignal replay]] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
}

- (void)_setupAllViewInViewLoad
{
    @weakify(self);
}

- (void)_setupAllView
{
    [self _setupTabsView];
    [self _setupTableScrollView];
}

- (void)_setupTabsView
{
    @weakify(self)
    
    CGSize tabContentScrollViewSize = self.tableScrollView.frame.size;
    
    NSMutableArray* tabInfos = [NSMutableArray array];
    for (NSInteger index=0; index<self.viewModel.tabInfos.count; index++)
    {
        NSDictionary* curTabInfo = self.viewModel.tabInfos[index];
        
        [tabInfos addObject:@{@"TabName":curTabInfo[@"TabName"]}];
    }
    
    EPMainTabsViewModel* vm = [[EPMainTabsViewModel alloc] init];
    vm.tabInfos = tabInfos;
    [vm.didClickTab subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSLog(@"TabsView select index : %d", [x integerValue]);
         
         NSInteger index = [x integerValue];
         
         self.viewModel.tabIndex = index;
         
         [self.tableScrollView scrollRectToVisible:(CGRect) {index*tabContentScrollViewSize.width, 0, tabContentScrollViewSize} animated:YES];
     }];
    
    EPMainTabsView* curView = [[EPMainTabsView alloc] initWithFrame:(CGRect) {0, 0, self.tabsView.frame.size}];
    [curView bindViewModel:vm];
    curView.tag = 99;
    [self.tabsView addSubview:curView];
}

- (void)_setupTableScrollView
{
    @weakify(self);
    
    NSMutableArray* newTableViews = [NSMutableArray array];
    
    NSInteger tCount = self.viewModel.tableVMs.count;
    for (NSInteger index=0; index<tCount; index++)
    {
        MyConsulationTableViewModel* curTableVM = self.viewModel.tableVMs[index];
        
        [[[[RACObserve(curTableVM, dataSource) distinctUntilChanged] filter:^BOOL(id value) {
            
            return value != nil;
        }] deliverOnMainThread]
         subscribeNext:^(id x) {
             @strongify(self)
             // 刷新数据
             
             NSArray* curArr = x;
             UITableView* curTableView = self.tableViews[index];
             UIImageView* emptyTipView = [curTableView viewWithTag:199];
             emptyTipView.hidden = curArr.count > 0;
             
             [self reloadListData:curTableVM.tag];
         }];
        
        curTableVM.didSelectCommand = curTableVM.selectCmd;
        
        [[curTableVM.selectCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
            @strongify(self)
            
            [self _push2ConsultDetailVC:x];
        }];
        
        UITableView* tableView = [[UITableView alloc] initWithFrame:(CGRect){index*self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height - 44.0f - 8.0f}];
        tableView.tag = 10 + index;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.delegate = self;
        tableView.dataSource = self;
        
        /// 添加加载和刷新控件
        if (curTableVM.shouldPullDownToRefresh) {
            /// 下拉刷新
            [tableView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
                /// 加载下拉刷新的数据
                @strongify(self);
                [self tableViewDidTriggerHeaderRefresh:curTableVM];
            }];
            [tableView.mj_header beginRefreshing];
        }
        
        if (curTableVM.shouldPullUpToLoadMore) {
            /// 上拉加载
            @weakify(self);
            [tableView mh_addFooterRefresh:^(MJRefreshAutoNormalFooter *footer) {
                /// 加载上拉刷新的数据
                @strongify(self);
                [self tableViewDidTriggerFooterRefresh:curTableVM];
            }];
            
            /// 判断一下数据
            [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:curTableVM];
        }
        
#ifdef __IPHONE_11_0
        MHAdjustsScrollViewInsets_Never(tableView);
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
#endif
        
        [tableView mh_registerNibCell:[ConsulationAnsedListCell class]];
        
        UIImage* emptyTipImg = MHImageNamed(@"baocuo");
        UIImageView* emptyTipView = [[UIImageView alloc] initWithImage:emptyTipImg];
        emptyTipView.hidden = YES;
        CGPoint centerPoint = (CGPoint) {self.view.frame.size.width/2.0f, self.view.frame.size.height/2.0f + 22.0f};
        CGSize viewSize = (CGSize) {100, emptyTipImg.size.height*100/emptyTipImg.size.width};
        emptyTipView.frame = (CGRect) {centerPoint.x - viewSize.width/2.0f, centerPoint.y - viewSize.height/2.0f, viewSize};
        emptyTipView.tag = 199;
        UILabel* tipLabel = [[UILabel alloc] initWithFrame:(CGRect) {16, viewSize.height + 24, viewSize.width, 24}];
        tipLabel.text = @"暂无记录";
        tipLabel.textColor = UIColorHex(#bbbbbb);
        [emptyTipView addSubview:tipLabel];
        [tableView addSubview:emptyTipView];
        
        [self.tableScrollView addSubview:tableView];
        
        [newTableViews addObject:tableView];
    }
    self.tableViews = newTableViews;
    
    self.tableScrollView.contentSize = (CGSize) {tCount*self.view.frame.size.width, self.view.frame.size.height - 44.0f - 8.0f};
    self.tableScrollView.pagingEnabled = YES;
    self.tableScrollView.alwaysBounceVertical = NO;
    self.tableScrollView.alwaysBounceHorizontal = NO;
    self.tableScrollView.delegate = self;
}

#pragma mark -- sub class can override it
/// 下拉事件
- (void)tableViewDidTriggerHeaderRefresh:(id)tvm
{
    @weakify(self)
    NSDictionary* info = @{@"LoadIndex":@(0)};
    
    MyConsulationTableViewModel* tableVM = tvm;
    [[[tableVM.requestDataCmd
       execute:info]
      deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self)
         tableVM.page = 1;
     } error:^(NSError *error) {
         @strongify(self)
         [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
     } completed:^{
         @strongify(self)
         /// 已经在bindViewModel中添加了对viewModel.dataSource的变化的监听来刷新数据
         [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
     }];
}

/// 上拉事件
- (void)tableViewDidTriggerFooterRefresh:(id)tvm
{
    @weakify(self);
    MyConsulationTableViewModel* tableVM = tvm;
    
    NSDictionary* info = @{@"LoadIndex":@(tableVM.page)};
    [[[tableVM.requestDataCmd
       execute:info]
      deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self)
         tableVM.page += 1;
     } error:^(NSError *error) {
         @strongify(self);
         [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
     } completed:^{
         @strongify(self)
         [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
     }];
}

/// 刷新完成事件
- (void)tableViewDidFinishTriggerHeader:(BOOL)isHeader reload:(BOOL)reload tableVM:(id)tvm
{
    NSInteger tag = 0;
    NSInteger page = 0;
    NSInteger lastPage = 0;
    
    MyConsulationTableViewModel* tableVM = tvm;
    tag = tableVM.tag;
    page = tableVM.page;
    lastPage = tableVM.lastPage;
    
    UITableView* findTableView = NULL;
    
    for (UITableView* curTableView in self.tableViews)
    {
        if (curTableView.tag == tag)
        {
            findTableView = curTableView;
            
            break;
        }
    }
    
    if (findTableView != NULL)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (reload) {
                [findTableView reloadData];
            }
            if (isHeader) {
                [findTableView.mj_header endRefreshing];
            }
            else{
                [findTableView.mj_footer endRefreshing];
            }
            /// 最后一页隐藏加载控件
            findTableView.mj_footer.hidden = (page>=lastPage);
        });
    }
}

- (UIEdgeInsets)contentInset{
    return UIEdgeInsetsMake(64, 0, 0, 0);
}

/// reload tableView data
- (void)reloadListData:(NSInteger)tag
{
    for (UITableView* curTableView in self.tableViews)
    {
        if (curTableView.tag == tag)
        {
            NSLog(@"ReloadData Tag : %d", tag);
            
            for (MyConsulationTableViewModel* curTVM in self.viewModel.tableVMs)
            {
                if (curTVM.tag == tag)
                {
                    NSLog(@"ReloadData dataSource : %d", curTVM.dataSource.count);
                    
                    break;
                }
            }
            
            [curTableView reloadData];
            
            break;
        }
    }
}

/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    NSString* strClass = NSStringFromClass([ConsulationAnsedListCell class]);
    
    return [tableView dequeueReusableCellWithIdentifier:strClass];
}

/// config  data
- (void)configureCell:(id)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    
    ConsulationAnsedListCell* curCell = cell;
    ConsulationAnsedListCellModel* curCellModel = object;
    
    [curCell bindViewModel:curCellModel];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    MyConsulationTableViewModel* curTableVM = NULL;
    for (MyConsulationTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            curTableVM = curTVM;
            
            break;
        }
    }
    
    if (curTableVM.shouldMultiSections) return curTableVM.dataSource ? curTableVM.dataSource.count : 1;
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = 0;
    
    MyConsulationTableViewModel* curTableVM = NULL;
    for (MyConsulationTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            curTableVM = curTVM;
            
            break;
        }
    }
    
    if (curTableVM.shouldMultiSections) return [curTableVM.dataSource[section] count];
    
    return curTableVM.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyConsulationTableViewModel* findTVM = NULL;
    for (MyConsulationTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            findTVM = curTVM;
            
            break;
        }
    }
    
    Class cellClass = [ConsulationAnsedListCell class];
    
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:NSStringFromClass(cellClass) forIndexPath:indexPath];
    
    // fetch object
    id object = nil;
    if (findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.section][indexPath.row];
    if (!findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.row];
    
    /// bind model
    [self configureCell:(ConsulationAnsedListCell*)cell atIndexPath:indexPath withObject:(id)object];
    
    return cell;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度

    for (MyConsulationTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (tableView.tag == curTVM.tag)
        {
            return [curTVM.dataSource[indexPath.row] cellHeight];
        }
    }

    return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // execute commond
    
    for (MyConsulationTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            [curTVM.didSelectCommand execute:curTVM.dataSource[indexPath.row]];
            
            return;
        }
    }
}

#pragma mark - 监听事件


#pragma mark - 跳转
- (void)_push2ConsultDetailVC:(id)cellModel
{
    ConsulationV2AnswerInfoViewModel* vm = [[ConsulationV2AnswerInfoViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"回复内容"}];
    vm.consultListData = cellModel;
    ConsulationV2AnswerInfoViewController* vc = [[ConsulationV2AnswerInfoViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

